package vip.xiaonuo.biz.modular.dict.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import org.springframework.stereotype.Service;
import vip.xiaonuo.biz.modular.dict.config.Kyutil;
import vip.xiaonuo.biz.modular.dict.entity.HbArea;
import vip.xiaonuo.biz.modular.dict.entity.dto.AlarmHomeDto;
import vip.xiaonuo.biz.modular.dict.mapper.HbAlarmMapper;
import vip.xiaonuo.biz.modular.dict.mapper.HbAreaMapper;
import vip.xiaonuo.biz.modular.dict.service.IHomeService;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 张奇
 * @desc
 * @time 2024/3/19 09:52
 */
@Service
public class HomeServiceImpl implements IHomeService {

    @Resource
    private HbAlarmMapper hbAlarmMapper;

    @Resource
    private HbAreaMapper hbAreaMapper;


    /**
     * 查询最新的20条告警记录
     *
     * @return
     */
    @Override
    public List<AlarmHomeDto> getHomeAlarmList() {
        List<AlarmHomeDto> alarmHomeDtos = hbAlarmMapper.selectByTime();
        return alarmHomeDtos;
    }

    /**
     * 查询告警数据统计
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return
     */
    @Override
    public Map<String, Object> getHomeCountList(String startTime, String endTime) {
        List<Map<String, Object>> levelCountList = hbAlarmMapper.countByLevelAndTime(startTime, endTime, null);

        List<String> areaList = new ArrayList<>();
        List<Integer> lowList = new ArrayList<>();
        List<Integer> mediumList = new ArrayList<>();
        List<Integer> highList = new ArrayList<>();

        for (HbArea hbArea : hbAreaMapper.selectList(null)) {
            if (hbArea.getAreaName().equals("13010400002160001011")) {
                continue;
            }
            areaList.add(hbArea.getAreaName());

            List<Map<String, Object>> areaLevelList = hbAlarmMapper.countByLevelAndTime(startTime, endTime, hbArea.getAreaName());
            if (areaLevelList.size() == 0){
                lowList.add(0);
                mediumList.add(0);
                highList.add(0);
            }
            for (Map<String, Object> stringObjectMap : areaLevelList) {
                if (MapUtil.getStr(stringObjectMap, "name").equals("低危")) {
                    lowList.add(MapUtil.getInt(stringObjectMap, "value"));
                }
                if (MapUtil.getStr(stringObjectMap, "name").equals("中危")) {
                    mediumList.add(MapUtil.getInt(stringObjectMap, "value"));
                }
                if (MapUtil.getStr(stringObjectMap, "name").equals("高危")) {
                    highList.add(MapUtil.getInt(stringObjectMap, "value"));
                }
            }
        }
        return MapUtil.builder(new HashMap<String, Object>())
                .put("levelCountList", levelCountList)
                .put("areaCountList", MapUtil.builder(new HashMap<String, Object>())
                        .put("areaList", areaList)
                        .put("lowList", lowList)
                        .put("mediumList", mediumList)
                        .put("highList", highList)
                        .build())
                .build();
    }

    @Override
    public JSONArray areaCreamAlarm() {

        //时间点获取   本月  本周  当日的 开始时间结束时间
        Calendar calendar = Calendar.getInstance();
        // 本月的开始时间和结束时间
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        Kyutil.setToBeginningOfDay(calendar);
        long monthStartTime = calendar.getTimeInMillis();

        calendar.add(Calendar.MONTH, 1);
        calendar.add(Calendar.DATE, -1);
        Kyutil.setToEndOfDay(calendar);
        long monthEndTime = calendar.getTimeInMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 设置日期格式
        List<HbArea> hbAreas = hbAreaMapper.selectList(null);
        List<String> areaNameList = hbAreas.stream().map(HbArea::getAreaName).collect(Collectors.toList());
        areaNameList.remove("河北公司");
        areaNameList.remove("13010400002160001011");
        List<Map<String, Object>> levelCountList = hbAlarmMapper.areaCreamAlarm(sdf.format(monthStartTime), sdf.format(monthEndTime),areaNameList);


        //过滤
        JSONArray respJsonArr = new JSONArray();


        for (String areaName : areaNameList) {
            JSONObject respJson = new JSONObject();
            List<Map<String, Object>> collect = levelCountList.stream()
                    .filter(map -> map.containsKey("areaName") && areaName.equals(map.get("areaName"))).collect(Collectors.toList());
            collect.forEach(System.out::println);
            respJson.putOnce("areaName",areaName);

            JSONArray alarmArrJson = new JSONArray();
            for (Map<String, Object> stringObjectMap : collect) {
                JSONObject alarmJson = new JSONObject();
                alarmJson.putOnce("alarmType",String.valueOf(stringObjectMap.get("alarmType")));
                alarmJson.putOnce("num",String.valueOf(stringObjectMap.get("num")));
                alarmArrJson.add(alarmJson);
                if(alarmArrJson.size()  == 3){
                    break;
                }
            }
            JSONObject alarmJson = new JSONObject();
            alarmJson.putOnce("arr",alarmArrJson);
            int sum = collect.stream()
                    .mapToInt(map -> Integer.valueOf(String.valueOf(map.getOrDefault("num", 0)))) // 将值映射为整数，并提取对应 key 的值，不存在则为默认值 0
                    .sum();

            alarmJson.putOnce("total",sum);
            respJson.putOnce("alarm",alarmJson);
            respJson.putOnce("status","32/12");
            respJsonArr.add(respJson);
        }


        return respJsonArr;
    }

    @Override
    public JSONObject alarmCount() {
        //时间点获取   本月  本周  当日的 开始时间结束时间
        Calendar calendar = Calendar.getInstance();
        // 本月的开始时间和结束时间
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        Kyutil.setToBeginningOfDay(calendar);
        long monthStartTime = calendar.getTimeInMillis();

        calendar.add(Calendar.MONTH, 1);
        calendar.add(Calendar.DATE, -1);
        Kyutil.setToEndOfDay(calendar);
        long monthEndTime = calendar.getTimeInMillis();

        // 本周的开始时间和结束时间
        calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());
        Kyutil.setToBeginningOfDay(calendar);
        long weekStartTime = calendar.getTimeInMillis();

        calendar.add(Calendar.DATE, 6);
        Kyutil.setToEndOfDay(calendar);
        long weekEndTime = calendar.getTimeInMillis();

        // 当日的开始时间和结束时间
        calendar = Calendar.getInstance();
        Kyutil.setToBeginningOfDay(calendar);
        long dayStartTime = calendar.getTimeInMillis();

        Kyutil.setToEndOfDay(calendar);
        long dayEndTime = calendar.getTimeInMillis();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String monthStartTimeStr = sdf.format(new Date(monthStartTime));
        String monthEndTimeStr = sdf.format(new Date(monthEndTime));
        String weekStartTimeTimeStr = sdf.format(new Date(weekStartTime));
        String weekEndTimeTimeStr = sdf.format(new Date(weekEndTime));
        String dayStartTimeTimeStr = sdf.format(new Date(dayStartTime));
        String dayEndTimeTimeStr = sdf.format(new Date(dayEndTime));
        System.out.println("本月开始时间：" + monthStartTime);
        System.out.println("本月结束时间：" + monthEndTime);
        System.out.println("本周开始时间：" + weekStartTime);
        System.out.println("本周结束时间：" + weekEndTime);
        System.out.println("当日开始时间：" + dayStartTime);
        System.out.println("当日结束时间：" + dayEndTime);

        Long dayLong = hbAlarmMapper.alarmCount(dayStartTimeTimeStr, dayEndTimeTimeStr);
        Long weekLong = hbAlarmMapper.alarmCount(weekStartTimeTimeStr, weekEndTimeTimeStr);
        Long monthLong = hbAlarmMapper.alarmCount(monthStartTimeStr, monthEndTimeStr);
        JSONObject respJson = new JSONObject();
        respJson.putOnce("day",dayLong);
        respJson.putOnce("week",weekLong);
        respJson.putOnce("month",monthLong);
        return respJson;
    }


}
